﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Png;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhiJiao.Models.Entities;
using ZhiJiao.Service.Abstracts;
using ZhiJiao.Service.Dto;

namespace ZhiJiao.Service.Services
{
    public class FileUploadService : IFileUploadService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly HttpContent _httpContent;
        private readonly IWebHostEnvironment _webHost;

        public FileUploadService(IHttpContextAccessor httpContextAccessor,
                                 IWebHostEnvironment webHost)
        {
            _httpContextAccessor = httpContextAccessor;
            _webHost = webHost;
        }

        public async Task<ImageDto> UploadMultiImageAsync()
        {
            List<ImageDto> images = new List<ImageDto>();
            var file = _httpContextAccessor.HttpContext!.Request.Form.Files[0];
            var image = new ImageDto();
                image.Name = file.FileName;
                image.Url = await CompressAndSave(file);
            return image;
        }

        /// <summary>
        /// 压缩保存
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public async Task<string> CompressAndSave(IFormFile file)
        {
            var fileName = Path.GetFileName(file.FileName);
            // 压缩后文件名
            var compressedFileName = $"{DateTime.Now.ToString("yyyyMMddhhmmss")}{Path.GetExtension(fileName)}";
            var rootPath = _webHost.WebRootPath;  // wwwroot 目录途径
            var compressedFilePath = Path.Combine(rootPath, "images", compressedFileName);

            using var fileStream = file.OpenReadStream();
            using (var image = Image.Load(fileStream))
            {
                var options = new PngEncoder
                {
                    CompressionLevel = PngCompressionLevel.NoCompression// 无损压缩
                };
                await image.SaveAsync(compressedFilePath, options);
            }

            return "/images/"+ compressedFileName;
        }


        public bool DeleteImage(ZJImage image)
         { 
            var rootPath = _webHost.WebRootPath;
            // 完整路径
            var imagePath =rootPath+ image.Url.Replace("/","\\");
            if (File.Exists(imagePath))
            {
                File.Delete(imagePath);
                return true;
            }
            else
            {
                throw new FileNotFoundException("The file does not exist.", imagePath);
            }
        }
    }
}
